package syllabus.shiro;



import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.google.common.base.Objects;

import syllabus.controller.LoginAct;
import syllabus.model.Criteria;
import syllabus.model.PPermission;
import syllabus.model.PRole;
import syllabus.model.PUser;
import syllabus.service.PPermissionService;
import syllabus.service.PRoleService;
import syllabus.service.PUserService;


public class ShiroDbRealm extends AuthorizingRealm{

	private static final Logger logger = LoggerFactory.getLogger(ShiroDbRealm.class);
	@Autowired
	protected PUserService userService;
	@Autowired
	protected PRoleService roleService;
	@Autowired
	protected PPermissionService permissionService;

	/**
	 * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) throws AuthenticationException{
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		//获取当前登录的用户名
		//String account = (String) super.getAvailablePrincipal(principals);
		ShiroUser shiroUser = (ShiroUser) principals.getPrimaryPrincipal();
		
		Criteria c = new Criteria();
		if(shiroUser != null){
			c.put("loginName", shiroUser.loginName);		
		}
		
		
		List<String> roles = new ArrayList<String>();  
		List<String> permissions = new ArrayList<String>();
		
		List<PRole> roleList = roleService.getRoles(c);
		for(PRole role : roleList){
			String roleName = role.getRoleName();
			if(StringUtils.isNotBlank(roleName)){
				roles.add(roleName);
				c.put("roleName", roleName);
				List<PPermission> pList = permissionService.getPermissions(c);
				for(PPermission p : pList){
					String permission = p.getPermission();
					if(StringUtils.isNotBlank(permission)){
						permissions.add(permission);
					}
				}
			}
		}
		/*User user = userService.getByAccount(account);
		if(user != null){
			if (user.getRoles() != null && user.getRoles().size() > 0) {
				for (Role role : user.getRoles()) {
					roles.add(role.getName());
					if (role.getPmss() != null && role.getPmss().size() > 0) {
						for (Permission pmss : role.getPmss()) {
							if(!StringUtils.isEmpty(pmss.getPermission())){
								permissions.add(pmss.getPermission());
							}
						}
					}
				}
			}
		}else{
			throw new AuthorizationException();
		}*/
		//给当前用户设置角色
		info.addRoles(roles);
		//给当前用户设置权限
        info.addStringPermissions(permissions); 
		return info;
	
	}
	/**
	 * 认证回调函数,登录时调用.
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken authcToken) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		//User user = userService.findUserByUsername(token.getUsername());
		String password = String.valueOf(token.getPassword());
		Criteria c = new Criteria();
		c.put("loginName", token.getUsername());
		c.put("password", password);
		PUser user = userService.selectByUser(c);
		if (user != null) {
			logger.info("用户{}" + user.getLoginName() + "登录。。。");
			return new SimpleAuthenticationInfo(new ShiroUser(user.getId(),user.getLoginName(),user.getUsername()), user.getPassword(), user.getUsername());
		} else {
			return null;
		}
	}

	/**
	 * 自定义Authentication对象，使得Subject除了携带用户的登录名外还可以携带更多信息.
	 */
	public static class ShiroUser implements Serializable {
		private static final long serialVersionUID = -1373760761780840081L;
		public Integer id;
		public String loginName;
		public String name;

		public ShiroUser(Integer id, String loginName, String name) {
			this.id = id;
			this.loginName = loginName;
			this.name = name;
		}

		public String getName() {
			return name;
		}

		/**
		 * 本函数输出将作为默认的<shiro:principal/>输出.
		 */
		@Override
		public String toString() {
			return loginName;
		}

		/**
		 * 重载hashCode,只计算loginName;
		 */
		@Override
		public int hashCode() {
			return Objects.hashCode(loginName);
		}

		/**
		 * 重载equals,只计算loginName;
		 */
		@Override
		public boolean equals(Object obj) {
			if (this == obj) {
				return true;
			}
			if (obj == null) {
				return false;
			}
			if (getClass() != obj.getClass()) {
				return false;
			}
			ShiroUser other = (ShiroUser) obj;
			if (loginName == null) {
				if (other.loginName != null) {
					return false;
				}
			} else if (!loginName.equals(other.loginName)) {
				return false;
			}
			return true;
		}
	}
	
	
}
